package com.skytech.component.crawler.word;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.skytech.component.crawler.scratch.base.PageContentService;
import com.skytech.component.crawler.scratch.base.PageView;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Service
public class HtmlToWordService {
    @Autowired
    private PageContentService pageContentService;

    public void createWord(HttpServletRequest request, HttpServletResponse response){
        JSONObject pageContentByCondition = pageContentService.findPageContentByCondition("", "", "", "", "", "", "", "", 10, 1);
        pageContentByCondition.getJSONArray("item");
        List<PageView> item = JSONArray.parseArray(pageContentByCondition.getJSONArray("item").toJSONString(), PageView.class);
        Resource resource = new ClassPathResource("templates/word.html");
        File file = null;
        try {
            file = resource.getFile();
            Document parse = Jsoup.parse(file, "UTF-8", "");
            for (PageView pageView : item) {
                parse.getElementById("crawler_title").append("<div>"+pageView.getTitle()+"</div>");
                parse.getElementById("crawler_content").append("<div>"+pageView.getContent()+"</div>");

            }
            byte b[] = parse.toString().getBytes("UTF-8");  //这里是必须要设置编码的，不然导出中文就会乱码。
            ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
            /*
             * 关键地方
             * 生成word格式 */
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            poifs.createDocument(bais, "WordDocument");

            //输出文件
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");//导出word格式
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    new String( ("文档名称" + ".doc").getBytes(),  "iso-8859-1"));
            OutputStream ostream = response.getOutputStream();
            poifs.writeFilesystem(ostream);
            bais.close();
            ostream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
